﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace Controllers
{
    public class ExamController : BaseController
    {
        //分页查询
        public ActionResult Find(int start, int limit)
        {
            IQueryable<ExamType> list = from r in ctx.ExamTypes select r;
            CJson CJson = new CJson();
            string json = CJson.ToJsonString("totalCount:" + list.Count() + ",data", list.Skip(start).Take(limit).ToList());
            return Content(json);
        }

        //删除
        public ActionResult Delete(int id)
        {
            var rdto = new ResultMessages();
            rdto.Message = "";
            ExamQuestion oriObj = ctx.ExamQuestions.Single(r => r.Id == id);
            ctx.ExamQuestions.DeleteOnSubmit(oriObj);
            try
            {
                ctx.SubmitChanges();
                rdto.Message = "删除成功";
                rdto.Result = true;
            }
            catch
            {
                rdto.Message = "删除失败";
                rdto.Result = false;
            }
            return Json(rdto);
        }

        //随机抽题
        public ActionResult RandomQuestion()
        {
            EmpBasicInfo ebi = Session["ebi"] as EmpBasicInfo;
            IQueryable<ExamQuestion> list= from r in ctx.ExamQuestions where !(from ea in ctx.ExamAnswers where ea.EmpId==ebi.Id select ea.QuestionId).Contains(r.Id) select r;
            int cnt = list.Count();
            DateTime dt = DateTime.Now;
            string st=dt.ToShortTimeString().Replace(":","");
            int i = int.Parse(st);
            if(cnt>0 && i<=1930)
            {
                Random ro = new Random();
                int skip = ro.Next(cnt);
                ExamQuestion obj = list.Skip(skip).Take(1).First();
                return Json(obj);
            }else if(cnt>0)
            {
                return Json("Time Over");
            }
            else
            {
                return Json("Test Over");
            }
        }

        //已做题数
        public ActionResult HasAnsweredNum()
        {
            EmpBasicInfo ebi = Session["ebi"] as EmpBasicInfo;
            int answeredNum = (from r in ctx.ExamAnswers where r.EmpId == ebi.Id select r).Count();
            return Json(answeredNum);
        }
        
        //保存答案
        public ActionResult SaveAnswer(string json)
        {
            var rdto = new ResultMessages();
            rdto.Message = "";
            JavaScriptSerializer jss = new JavaScriptSerializer();
            try
            {
                ExamAnswer obj = jss.Deserialize<ExamAnswer>(json);
                EmpBasicInfo ebi = Session["ebi"] as EmpBasicInfo;
                ExamAnswer ea = ctx.ExamAnswers.SingleOrDefault(r => r.EmpId == ebi.Id && r.QuestionId == obj.QuestionId);
                if (ea==null)
                {
                    obj.EmpId = ebi.Id;
                    ctx.ExamAnswers.InsertOnSubmit(obj);
                }
                else
                {
                    ea.Answer = obj.Answer;
                }
                ctx.SubmitChanges();
                rdto.Message = "保存成功";
                rdto.Result = true;
            }
            catch (Exception ex)
            {
                rdto.Message = "保存失败";
                rdto.Result = false;
            }
            return Json(rdto);
        }

        class Result
        {
            public string Name { get; set; }
            public decimal Score { get; set; }
        }
        //分数统计
        public ActionResult ScoreStat()
        {
            IEnumerable<Result> results = ctx.ExecuteQuery<Result>(@"select Name,Score from
(select EmpId,SUM(Score) Score from(
SELECT b.EmpId,a.Id,QuestionType,a.Answer,b.Answer bAnswer,
      case when a.Answer=b.Answer and a.QuestionType='判断题' then 0.5
      when a.Answer=b.Answer and a.QuestionType='单项选择题' then 2
      when a.Answer=b.Answer and a.QuestionType='多项选择题' then 3 else 0 end Score
  FROM ExamQuestions a inner join ExamAnswers b on a.Id=b.QuestionId) t
  group by EmpId) t2 inner join Employee c on t2.EmpId=c.Id
  order by Name");
            return Json(results);
        }

        //试卷授权
        public ActionResult AuthOpt(int id, string empIds)
        {
            string retStr = "Succeed";
            ExamType examType = ctx.ExamTypes.Single(r => r.Id == id);
            examType.Testers = empIds;
            ctx.SubmitChanges();
            return Json(retStr);
        }
    }
}